﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Principal;
using System.Web.Http;
using Monitor.Models.Json;
using ServiceStack.Text;

namespace Monitor.Controllers.ApiControllers.Administrator
{
    public class BakController : MainApiController
    {
        
        #region Get

        // GET data/bak/5
        public BakOutput Get(Int64 id)
        {
            try
            {
                var query = DataRepository.BakRepository.GetBak(id);
                if (query != null)
                {
                    return new BakOutput()
                               {
                                   Id = query.BakId,
                                   Date = query.Date,
                                   SerialNumber = query.SerialNumber,
                                   Type = query.ClassifType.FullName,
                                   TypeId = query.Type,
                                   Creator = query.Produser,
                                   Expluat =
                                       DataRepository.ClassificatorRepository.GetById(
                                           query.OperationOrganization).FullName,
                                   ExpluatId = query.OperationOrganization
                               };
                }
            }
            catch (Exception e)
            {
                ErrorLogger.Fatal(this.ControllerContext, e);
            }
            return null;
        }

        public IEnumerable<BakOutput> Get(bool free)
        {
            try
            {
                var filter = (free) ?DataRepository.BakRepository.FreeBak :null;
                return filter.Select(query=> new BakOutput()
                    {
                        Id = query.BakId,
                        Date = query.Date,
                        SerialNumber = query.SerialNumber,
                        Type = query.ClassifType.FullName,
                        TypeId = query.Type,
                        Creator = query.Produser,
                        Expluat =
                            DataRepository.ClassificatorRepository.GetById(
                                query.OperationOrganization).FullName,
                        ExpluatId = query.OperationOrganization
                    });
            }
            catch (Exception e)
            {
                ErrorLogger.Fatal(this.ControllerContext, e);
            }
            return null;
        }

        // GET data/bak
        public GetSumBak Get([FromUri]int pagenum, [FromUri] int pagesize)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var dbResult = DataRepository
                        .BakRepository
                        .GetBak();
                    return new GetSumBak
                               {
                                   TotalRows = dbResult.Count(),
                                   Rows = dbResult.Skip(pagenum*pagesize)
                                       .Take(pagesize)
                                       .ToList()
                                       .Select(n => new BakOutput()
                                                        {
                                                            Id = n.BakId,
                                                            SerialNumber = n.SerialNumber,
                                                            Date = n.Date,
                                                            Type = n.ClassifType.FullName,
                                                            Creator = n.Produser,
                                                            TypeId = n.Type,
                                                            ExpluatId = n.OperationOrganization,
                                                            Expluat =
                                                                DataRepository.ClassificatorRepository.GetById(
                                                                    n.OperationOrganization).FullName
                                                        })
                                       .ToArray()
                               };
                }
                return null;
            }
            catch (Exception e)
            {
                ErrorLogger.Error(this.ControllerContext, e);
                return null;
            }

        }


        #endregion

        #region Добавить/изменить

        // PUT data/bak/5
        public HttpResponseMessage Put(BakInput model)
        {
            if (model.IsValid)
            {
                try
                {
                    if(!model.Id.HasValue)
                    {
                        DataRepository.BakRepository.AddBak(model);
                    }
                    else
                    {
                        DataRepository.BakRepository.EditBak(model);
                    }
                }
                catch (IdentityNotMappedException e)
                {
                    return Request.CreateResponse(HttpStatusCode.Conflict, e.Message);
                }
                catch (Exception e)
                {
                    ErrorLogger.Fatal(this.ControllerContext,e);
                    return Request.CreateResponse(HttpStatusCode.Conflict,"Извините, пожалуйста, но произошла ошибка при на сервере. Администратор уже оповещен.");
                }
                return Request.CreateResponse(HttpStatusCode.OK);
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.Forbidden, "Ошибка в данных");
            }
            
        }

        #endregion

        #region Удаление

        // DELETE api/bak/5
        public HttpResponseMessage Delete(Int64 id)
        {
            try
            {
                DataRepository.BakRepository.DeleteBak(id);
                return Request.CreateResponse(HttpStatusCode.OK);
            }
            catch (Exception e)
            {
                ErrorLogger.Fatal(this.ControllerContext, e);
                return Request.CreateResponse(HttpStatusCode.Conflict, "Извините, пожалуйста, но произошла ошибка при на сервере. Администратор уже оповещен.");
            }
            
        }

        #endregion
    }
}
